<?php
namespace App\Repositories;
use App\Events\AccessRemoved;
use App\Events\AccessStored;
use App\Model\Access as AccessModel;
use Illuminate\Validation\ValidationException;

class Access implements Repository
{
	public function store($data,$notify){

		if(isset($data["id"])){
			
			$access=AccessModel::where("id",$data["id"])->first();
			
			$access->update($data);

			$notify["method"]="edit";
		}else{
		
			$access=AccessModel::create($data);
			
			$notify["method"]="add";
		}
		
		event(new AccessStored($access,$notify));
		
		return true;
		
	}
	public function remove($data,$notify)	{
		
		if(!$accesses=AccessModel::where(function($query) use ($data){
			$query->whereIn('id', $data);
			$query->orWhereIn("parent_id",$data);
        })->get()){
			return true;
		}
	  
		AccessModel::where(function($query) use ($data){
			$query->whereIn('id', $data);
			$query->orWhereIn("parent_id",$data);
        })->delete();
		
	  foreach($accesses as $access){
		  
		  $access->menus()->detach();//菜单id
		  
		  $access->roles()->detach();//角色id
	  }
	  
	  $notify["method"]="remove";
		
	  event(new AccessRemoved($accesses,$notify));
		  
	  return true;

	}
	public function uri($data,$notify=[])	{
		return $data;
	}
}
